<?php
class NYAction
{
	public $user;
	private $conn;
	private $site;

	public function __construct( $site = 'raybt.loc' )
	{
		global $conn;
		$this->conn = $conn;
		$this->site = $site;
	}

	public function getUserById( $user_id )
	{
		$this->conn->query( sprintf( "SELECT * FROM users WHERE id=%d", $user_id ) );
		$this->user = $this->conn->fetch();
	}

	public function getUser( $email )
	{
		$this->conn->query( sprintf( "SELECT * FROM users WHERE email='%s'", $email ) );
		$this->user = $this->conn->fetch();
	}

	private function isUserWithoutPassword()
	{
		// if user without password, return true, else false:
		return ( !isset( $this->user->password ) || $this->user->password == 'no' );
	}

	private function newUser( $name, $email )
	{
		return $this->conn->query( sprintf( "INSERT INTO users SET name='%s',email='%s',password='%s',date_registred=NOW(),group_id=(SELECT id FROM groups WHERE type = 'users' AND name_sys = 'buyer')",
			mysql_escape_string( $name ), mysql_escape_string( $email ), 'no' ), true );
	}

	private function newConfirmation( $user_id, $email, $password, $uniqid )
	{
		if ( isset( $user_id ) )
			$this->conn->query( sprintf( "INSERT INTO users_confirm SET id=%d,email='%s',password='%s',uniqid='%s',reg_date=NOW()",
				$user_id, $email, $password, $uniqid ) );
	}

	private function mailConfirmation( $user_id, $name, $email, $uniqid, $is_new )
	{
		$subject = 'Регистрация на сайте РайБТ';
		$message = sprintf( "
		<h2>Подтверждение регистрации</h2>
		%s<br>
		<a href='http://%s/?ajax=ny_register&uid=%s&confirm=%s&n=%s'>Пожалуйста, пройдите по этой ссылке!</a>",
			$name, $this->site, $user_id, $uniqid, $is_new ? 'y' : 'n' );

		global $load;
		if ( !empty( $email ) )
			$load->module( 'email', 'send', array( 'mail_to' => $email, 'subject' => $subject, 'message' => $message ) );
	}

	public function setBonus( $email, $bonus = 50 )
	{
		$this->getUser( $email );
		// if user hasn't set bonus yet, then give it:
		if ( isset( $this->user->id ) && !isset( $this->user->bonus ) )
			$this->conn->query( sprintf( "UPDATE users SET bonus=%d WHERE id=%d", $bonus, $this->user->id ) );
	}

	public function sendConfirmation( $name, $email, $password )
	{
		$uniqid   = uniqid();
		$password = md5( $password );
		$this->getUser( $email );
		if ( isset( $this->user->id ) )
		{
			if ( $this->isUserWithoutPassword() )
			{ // user exists, but without password, just send confirmation of new password:
				$this->newConfirmation( $this->user->id, $email, $password, $uniqid );
				$this->mailConfirmation( $this->user->id, $name, $email, $uniqid, false );
			}
		}
		else
		{
			// add new user without password (password='no') until confirmation:
			$user_id = $this->newUser( $name, $email );
			$this->newConfirmation( $user_id, $email, $password, $uniqid );
			$this->mailConfirmation( $user_id, $name, $email, $uniqid, true );
		}
	}

	public static function checkFields( $fields )
	{
		$err      = array();
		$name     = isset( $fields[ 'name' ] ) ? trim( $fields[ 'name' ] ) : '';
		$email    = trim( $fields[ 'email' ] );
		$password = trim( $fields[ 'password' ] );

		if ( !$name || $name == 'Ваше Ф.И.О' )
			$err[ ] = 'Имя: значение не указано';

		if ( !$email && !preg_match( '#^[\w][-\w\.]*@[\w][-\w]+\.+[a-z]{2,4}$#', $email ) )
			$err[ ] = 'Почта: значение не указано или недопустимое значение';

		if ( !$password || $password == 'пароль' )
			$err[ ] = 'Пароль: значение не указано';

		return $err;
	}

	public static function prepareErrors( array $errors )
	{
		$error_mess = '';
		foreach ( $errors as $error )
			$error_mess .= '<li>' . $error . '</li>';

		$error_mess  = ( !isset( $errors[ 'email_exist' ] ) ) ? $error_mess : $errors[ 'email_exist' ];
		$errors_mess = '<strong>Обнаружены следующие ошибки:</strong> <ul>' . $error_mess . '</ul>';
		return $errors_mess;
	}

	public function moveConfirmedPassword( $user_id, $uniqid )
	{
		// find user:
		$this->conn->query( sprintf( "SELECT * FROM users_confirm WHERE id=%d AND uniqid='%s'", $user_id, $uniqid ), false, 1000 );
		$row = $this->conn->fetch( 1000 );

		if ( isset( $row->uniqid ) && $row->uniqid == $uniqid )
		{
			// move user's password from users_confirm into users:
			$this->conn->query( sprintf( "UPDATE users SET password='%s' WHERE id=%d", $row->password, $user_id ) );

			// delete user's confirmation:
			$this->conn->query( sprintf( "DELETE FROM users_confirm WHERE id=%d", $user_id ) );
			return true;
		}
		return false;
	}

	public static function getForm()
	{
		?>
		<div class="global-popup__description">
				<span class="global-popup__close">
					<span>Закрыть</span>
				</span>
			<h2 class="big-title">Регистрация</h2>
			<div class="feedback_div ny_register_div">
				<form action="" id="ny_register_form">
					<fieldset>
						<input class="type-text" name="ny_register[name]" type="text" placeholder="ваше Ф.И.О">
					</fieldset>
					<fieldset>
						<input class="type-text" name="ny_register[email]" type="text" placeholder="эл.почта">
					</fieldset>
					<fieldset>
						<input class="type-text" name="ny_register[password]" type="password" placeholder="пароль">
					</fieldset>
					<fieldset>
						<input id="ny_register_button" class="global-button" type="submit" value="Зарегистрироваться">
					</fieldset>
				</form>
			</div>
			<div class="submit_form_loader_one_click">
				<div class="submit_form_loader loader">Обработка данных</div>
				<div class="response">
					<div class="successful"></div>
					<div class="errors"></div>
				</div>
			</div>
		</div>
		<div class="global-popup__popup-overlay">&nbsp;</div>
	<?php
	}

	public static function showMessage()
	{
		// remove message:
		$msg = $_COOKIE[ 'cookie_message' ];
		unset( $_COOKIE[ 'cookie_message' ] );
		?>
		<div class="global-popup__description">
				<span class="global-popup__close">
					<span>Закрыть</span>
				</span>
			<h2 class="big-title">Сообщения</h2>
			<div class="feedback_div ny_register_div">
			</div>
			<div class="submit_form_loader_one_click">
				<div class="response">
					<div class="successful"><?= json_decode( unserialize( $msg ) ); ?></div>
					<div class="errors"></div>
				</div>
			</div>
		</div>
		<div class="global-popup__popup-overlay">&nbsp;</div>
	<?php
	}
}

// ENTRY POINT...

if ( isset( $_POST[ 'action' ] ) )
{
	switch ( $_POST[ 'action' ] )
	{
		case 'get_form';
			NYAction::getForm();
			break;
		case 'message';
			NYAction::showMessage();
			break;
	}
}
elseif ( isset( $_GET[ 'uid' ] ) && isset( $_GET[ 'confirm' ] ) )
{
	$user_id          = $_GET[ 'uid' ];
	$uniqid           = $_GET[ 'confirm' ];
	$is_existing_user = $_GET[ 'n' ] == 'n' ? true : false;

	$ny_action = new NYAction();
	$ny_action->getUserById( $user_id );
	if ( $ny_action->moveConfirmedPassword( $user_id, $uniqid ) )
	{
		// give bonus:
		$bonus = $is_existing_user ? 100 : 50;
		$ny_action->setBonus( $ny_action->user->email, $bonus );

		// login:
		$ny_action->getUserById( $user_id );
		$user = new User( $conn );
		$user->login( $ny_action->user->email, $ny_action->user->password, true );

		// create new basket:
		del_cookie_basket_id();
		setBasketId();

		// display message:
		successRedirect( array( 'cookie_message' => json_encode( 'Ваша регистрация подтверждена! Вам начислено ' . $bonus . ' бонусов.' ), 'url' => '/bonusnaya-akciya' ) );
	}
}
else
{
	if ( isset( $_POST[ 'ny_register' ] ) )
	{
		$ny_register = array_map( 'trim', $_POST[ 'ny_register' ] );
		$errors      = NYAction::checkFields( $ny_register );

		if ( count( $errors ) == 0 )
		{
			$ny_action = new NYAction( SITE_NAME );
			$ny_action->sendConfirmation( $ny_register[ 'name' ], $ny_register[ 'email' ], $ny_register[ 'password' ] );
			disp_status( 'На вашу почту отправлена ссылка для подтверждения!' );
		}
		else
			disp_status( NYAction::prepareErrors( $errors ), 'true' );
	}
	// done: если ящик найден, но без пароля то 100
	// done: если ящик не найден и пользовател прошел регистрацию, то 50
} ?>